﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Shake.Framework.Utility
{
    public class ReflectUtil
    {
        public static List<Type> GetClassByInterface<T>()
        {
            var type = typeof(T);
            if (!type.IsInterface) throw new Exception("T应该是个接口");

            var features = FeatureUtil.GetFeatureAssembly().ToList();
            var results = new List<Type>();

            foreach (var feature in features)
            {
                try
                {
                    var classes = feature.ExportedTypes.Where(t => t.GetInterface(type.Name) != null).ToList();
                    if (classes.Count == 0) continue;

                    results.AddRange(classes);
                }
                catch (Exception ex)
                {
                    NLogUtil.Error(ex, "");
                }

            }
            return results;
        }

        public static List<Type> GetClassByAttribute<T>()
        {
            var type = typeof(T);
            var features = FeatureUtil.GetFeatureAssembly();
            var results = new List<Type>();

            foreach (var feature in features)
            {
                var classes = feature.ExportedTypes.Where(t => t.GetCustomAttributes(type, false).Length > 0).ToList();
                if (classes.Count == 0) continue;

                results.AddRange(classes);
            }
            return results;
        }

        public static List<Type> GetClassByBaseType<T>()
        {
            var type = typeof(T);
            var features = FeatureUtil.GetFeatureAssembly();
            var results = new List<Type>();

            foreach (var feature in features)
            {
                var classes = feature.ExportedTypes.Where(t => t.BaseType == type).ToList();
                if (classes.Count == 0) continue;

                results.AddRange(classes);
            }
            return results;
        }
    }
}
